package com.ja.openchat.ui.chat.group;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.FileDisplayActivity;
import com.ja.openchat.ui.chat.MessageViewModel;
import com.ja.openchat.ui.chat.PreviewMediaActivity;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.chat.audio.AudioPlayManager;
import com.ja.openchat.ui.chat.audio.IAudioPlayListener;
import com.ja.openchat.ui.chat.group.adapter.GroupSettingChildAdapter;
import com.ja.openchat.ui.chat.group.adapter.GroupSettingOfMembersAdapter;
import com.ja.openchat.viewmodels.GroupSettingViewModel;
import com.ja.openchat.views.AppFileReaderView;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.file.DocumentInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.group.JsoupTaskEvent;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.SearchMessagesFilter;
import com.zy.openchat.util.Common;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class GroupSettingChildFragment extends SettingFragment {

    public static GroupSettingChildFragment newInstance(int position, ChatInfo chatInfo){
        GroupSettingChildFragment fragment = new GroupSettingChildFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("chat",chatInfo);
        bundle.putInt("position",position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_group_setting_child;
    }

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private int pageIndex = 0;
    private GroupSettingViewModel groupSettingViewModel;

    private ChatInfo conversation;
    @Override
    protected void initDataAndEvent(Bundle savedInstanceState) {
        if(getArguments()!=null){
            pageIndex = getArguments().getInt("position");
            conversation = getArguments().getParcelable("chat");
        }
        ((SimpleItemAnimator)recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        if(pageIndex ==0){
            wrapperMembers();
        }else{
            wrapperMessages();
        }
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onJsoupEvent(JsoupTaskEvent event){
        if(pageIndex == 4&&event!=null&&!TextUtils.isEmpty(event.url)&&event.documentInfo!=null&&messageAdapter!=null&&messageAdapter.getData()!=null){
            List<MessageInfo> messageInfos = messageAdapter.getData();
            for(MessageInfo messageInfo: messageInfos){
                if(event.url.equals(JsoupTaskCallback.checkUrl(messageInfo.textTypeContent))){
                    messageInfo.setHtmlDocumentInfo(event.documentInfo);
                }
            }
            messageAdapter.notifyDataSetChanged();
        }
    }

    public void onTgEvent(final TgEvent tg_event){
        if(tg_event==null){
            return;
        }

        switch (tg_event.event) {
            case EUser_Td_Contact_Photo_Ok:
                if(groupSettingOfMembersAdapter!=null){
                    groupSettingOfMembersAdapter.notifyDataSetChanged();
                }
                break;
            case EUser_Td_Message_Photo_Ok:
            case EUser_Td_Message_Video_Ok:
            case EUser_Td_Message_Audio_Ok:
            case EUser_Td_Message_Voice_Ok:
            case EUser_Td_Message_Preview_Photo_Ok:
            case EUser_Td_Message_Document_Ok:
            case EUser_Td_Message_Animation_Ok:
                try {
                    if(messageAdapter!=null&&tg_event.data instanceof FileTaskInfo &&tg_event.dataEx instanceof FileInfo){
                        FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                        String ids = ((FileTaskInfo)tg_event.data).id;
                        if(!TextUtils.isEmpty(ids)&&ids.contains("_")){
                            String[] idArray = ids.split("_");
                            if(idArray.length >= 2){
                                if(idArray[0].equals(String.valueOf(conversation.id))){
                                    for(int i = 0; i< messageAdapter.getData().size();i++){
                                        MessageInfo message = messageAdapter.getItem(i);
                                        if(message.id == Long.parseLong(idArray[1])){
                                            switch (tg_event.event) {
                                                case EUser_Td_Message_Photo_Ok:
                                                    message.updateMessagePhotoFile(fileInfo);
                                                    break;
                                                case EUser_Td_Message_Preview_Photo_Ok:
                                                    message.updatePreviewPhotoFile(fileInfo);
                                                    break;
                                                case EUser_Td_Message_Video_Ok:
                                                    message.updateVideoFile(fileInfo);
                                                    break;
                                                case EUser_Td_Message_Document_Ok:
                                                    message.updateDocumentFile(fileInfo);
                                                    break;
                                                case EUser_Td_Message_Animation_Ok:
                                                    message.updateAnimationFile(fileInfo);
                                                    break;
                                                default:
                                                    message.updateAudioFile(fileInfo);
                                                    break;

                                            }
                                            messageAdapter.notifyItemChanged(i);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
        }
    }

    private static final int MESSAGE_LOAD_AROUND = 50;
    private long mFocusMessageId = 0;
    private void requestChatData(long focusMessageId){
        TelegramManager.getTelegramManager().searchChatMessages(getContext(),conversation.id, SearchMessagesFilter.attachUserHome(pageIndex-1) ,focusMessageId,null, 0, MESSAGE_LOAD_AROUND, new TgResultBlock<List<MessageInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                if(obj!=null&&obj.size()>0){
                    mFocusMessageId = obj.get(obj.size()-1).id;
                    if(focusMessageId==0){
                        messageAdapter.setNewData(obj);
                    }else{
                        messageAdapter.addData(obj);
                    }
                    messageAdapter.getLoadMoreModule().loadMoreComplete();
                }else{
                    messageAdapter.getLoadMoreModule().loadMoreEnd(true);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                messageAdapter.getLoadMoreModule().loadMoreEnd(true);
            }
        });
    }

    private boolean isMatch(MessageInfo messageInfo){
        if(pageIndex ==1){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo||messageInfo.messageType == TelegramManager.MessageType.MessageType_Video;
        }else if(pageIndex ==2){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Document;
        }else if(pageIndex ==3){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Audio;
        }else if(pageIndex ==4){
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Text && MessageViewModel.isLinkString(messageInfo.textTypeContent);
        }else{
            return messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation;
        }
    }

    private GroupSettingChildAdapter messageAdapter;
    private void wrapperMessages(){
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(),3));
        messageAdapter = new GroupSettingChildAdapter();
        recyclerView.setAdapter(messageAdapter);
        messageAdapter.setEmptyView(R.layout.status_center_empty_view_wrap);
        messageAdapter.getLoadMoreModule().setEnableLoadMore(true);
        messageAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                requestChatData(mFocusMessageId);
            }
        });
        messageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                MessageInfo messageInfo = messageAdapter.getItem(position);
                if(pageIndex == 1){
                    PreviewMediaActivity.previewMedia(getContext(),messageAdapter.getData(),position);
                }else if(pageIndex == 2){
                    if(messageInfo.content!=null&&messageInfo.content.document!=null){
                        DocumentInfo documentInfo = messageInfo.content.document;
                        if(!documentInfo.isFileDownloaded()){
                            ToastUtils.showShort(getString(R.string.file_downloading_text));
                            TelegramManager.getTelegramManager().downloadFile(messageInfo.chat_id+"_" + messageInfo.id, documentInfo.document.id, 0, TelegramManager.FileType.FileType_Message_Document);
                            return;
                        }
                        if(DocumentInfo.isImageFile(documentInfo.file_name)||DocumentInfo.isVideoFile(documentInfo.file_name)){
                            PreviewMediaActivity.previewImage(getContext(),messageInfo);
                        }else{
                            String fileExtension = AppFileReaderView.getFileType(documentInfo.file_name);
                            FileDisplayActivity.startActivity(getContext(),documentInfo.localFilePath(),fileExtension);
                        }
                    }
                }else if(pageIndex == 3){
                    if (!messageInfo.isAudioFileDownloaded()) {
                        TelegramManager.getTelegramManager().downloadFile(messageInfo.chat_id+"_" + messageInfo.id, messageInfo.getAudioFileId(), 0, TelegramManager.FileType.FileType_Message_Audio);
                        ToastUtils.showShort(getString(R.string.file_downloading_text));
                        return;
                    }
                    File file = new File(messageInfo.audioLocalPath());
                    playAudio(messageInfo,file);
                }else if(pageIndex == 4){
                    String link = messageInfo.textTypeContent;
                    PreviewWebViewActivity.loadUrl(getContext(), "", link);
                }else{
                    PreviewMediaActivity.previewMedia(getContext(),messageAdapter.getData(),position);
                }
            }
        });
        requestChatData(mFocusMessageId);
    }

    private void playAudio(MessageInfo message, File file) {
        Uri uri = Uri.fromFile(file);
        AudioPlayManager.getInstance().startPlay(App.getInstanse(), uri, new IAudioPlayListener() {

            @Override
            public void onStart(Uri var1, int lengthoftime) {

            }

            @Override
            public void onStop(Uri var1) {
                if (uri.equals(var1)) {

                }
            }

            @Override
            public void onProgress(Uri var1, int currentPosition, int secendProssed, int totalLenght) {

            }

            @Override
            public void onComplete(Uri var1) {
                if (uri.equals(var1)) {

                }
            }
        });
    }


    private Observer<List<GroupMemberInfo>> groupMembersObserver ;
    private GroupSettingOfMembersAdapter groupSettingOfMembersAdapter;
    private void wrapperMembers(){
        groupSettingViewModel = ViewModelProviders.of(getActivity()).get(GroupSettingViewModel.class);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        groupSettingOfMembersAdapter = new GroupSettingOfMembersAdapter();
        groupSettingOfMembersAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                GroupMemberInfo memberInfo = groupSettingOfMembersAdapter.getItem(position);
                if(memberInfo!=null&&getActivity()!=null&&getActivity() instanceof GroupChatSettingsNewActivity){
                    ((GroupChatSettingsNewActivity)getActivity()).clickMember(memberInfo,false);
                }
            }
        });
        recyclerView.setAdapter(groupSettingOfMembersAdapter);
        groupSettingOfMembersAdapter.setEmptyView(R.layout.status_center_empty_view_wrap);
        groupMembersObserver = new Observer<List<GroupMemberInfo>>() {

            @Override
            public void onChanged(List<GroupMemberInfo> groupMemberInfos) {
                if(!Common.isEmpty(groupMemberInfos)){
                    Collections.sort(groupMemberInfos, new Comparator<GroupMemberInfo>() {
                        @Override
                        public int compare(GroupMemberInfo ct1, GroupMemberInfo ct2) {
                            int index1 = ct1.isCreatorRole()?2:ct1.isManagerRole()?1:0;
                            int index2 = ct2.isCreatorRole()?2:ct2.isManagerRole()?1:0;
                            return index2 - index1;
                        }
                    });
                }
                groupSettingOfMembersAdapter.setNewData(groupMemberInfos);
            }
        };
        groupSettingViewModel.groupInfoLiveData().observeForever(groupMembersObserver);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if(groupMembersObserver!=null&&groupSettingViewModel!=null){
            groupSettingViewModel.groupInfoLiveData().removeObserver(groupMembersObserver);
        }
    }
}
